<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * @descrption: 弹出对话框，并返回上一个页面
 * @param $msg
 * @param $url
 * @author : da.liu
 */
function _alert($msg,$url=''){
    if($url == ''){
        $js = "window.history.back();";
    }else{
        $js = "window.location.href='".$url."'";
    }
    echo '<!DOCTYPE html>
<html>
<head lang="zh-cn">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta content="telephone=no" name="format-detection">';
    echo '<body>';
    echo '<script type="text/javascript" src="http://ofqj1epjb.bkt.clouddn.com/extends/jquery/jquery-1.9.1.min.js"></script>';
    echo '<script type="text/javascript" src="http://ofqj1epjb.bkt.clouddn.com/extends/layer/layer.js"></script>';
    echo '<script type="text/javascript">';
    echo "layer.open({content: '".$msg."',btn: ['确认'],shadeClose: false,yes: function(){{$js}}});";
    echo '</script></body></html>';
    exit;
}




//将URL中的参数取出来放到数组里
function convertUrlQuery($query){
    $queryParts = explode('&', $query);
    $params = array();
    foreach ($queryParts as $param){
        $item = explode('=', $param);
        $params[$item[0]] = $item[1];
    }
    return $params;
}


function _failure($msg){
    if(\think\facade\Request::isPost() || \think\facade\Request::isAjax()){
        $data = array('status'=>0,'msg'=>$msg,'info'=>$msg);
        // 返回JSON数据格式到客户端
        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($data));
    }else{
        _alert($msg);
    }

}


function _success($msg,$url=''){
    $data = array('status'=>1,'msg'=>$msg,'url'=>$url,'info'=>$msg);
    // 返回JSON数据格式到客户端
    header('Content-Type:application/json; charset=utf-8');
    exit(json_encode($data));
}

function remove_xss($val) {
    // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
    // this prevents some character re-spacing such as <java\0script>
    // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
    $val = preg_replace('/([\x00-\x08\x0b-\x0c\x0e-\x19])/', '', $val);
    // straight replacements, the user should never need these since they're normal characters
    // this prevents like <IMG SRC=@avascript:alert('XSS')>
    $search = 'abcdefghijklmnopqrstuvwxyz';
    $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $search .= '1234567890!@#$%^&*()';
    $search .= '~`";:?+/={}[]-_|\'\\';
    for ($i = 0; $i < strlen($search); $i++) {
        // ;? matches the ;, which is optional
        // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
        // @ @ search for the hex values
        $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
        // @ @ 0{0,7} matches '0' zero to seven times
        $val = preg_replace('/(�{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
    }
    // now the only remaining whitespace attacks are \t, \n, and \r
    $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
    $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $ra = array_merge($ra1, $ra2);
    $found = true; // keep replacing as long as the previous round replaced something
    while ($found == true) {
        $val_before = $val;
        for ($i = 0; $i < sizeof($ra); $i++) {
            $pattern = '/';
            for ($j = 0; $j < strlen($ra[$i]); $j++) {
                if ($j > 0) {
                    $pattern .= '(';
                    $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                    $pattern .= '|';
                    $pattern .= '|(�{0,8}([9|10|13]);)';
                    $pattern .= ')*';
                }
                $pattern .= $ra[$i][$j];
            }
            $pattern .= '/i';
            $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
            $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
            if ($val_before == $val) {
                // no replacements were made, so exit the loop
                $found = false;
            }
        }
    }
    return $val;
}


function get_max_number($number){
    return floor($number / 60);
}

/**
 * 秒转换成分钟
 * @param type $time
 * @return string
 */
function Sec2Time($time){
    if(is_numeric($time)){
        $str = '';
        if($time >= 3600){
            $str.=floor($time/3600).'小时';
            $time = ($time%3600);
        }
        if($time >= 60){
            $str.= floor($time/60).'分钟';
            $time = ($time%60);
        }
        $str.= floor($time).'秒';
        return $str;
    }
}

//数组排序
function my_sort($arrays,$sort_key,$sort_order=SORT_DESC,$sort_type=SORT_NUMERIC ){
    if(is_array($arrays)){
        foreach ($arrays as $array){
            if(is_array($array)){
                $key_arrays[] = $array[$sort_key];
            }else{
                return false;
            }
        }
    }else{
        return false;
    }
    array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
    return $arrays;
}

//ip转换
function ip_long($ip){
    return bindec( decbin( ip2long( $ip ) ) );
}


function emoji2str($str){
    $strEncode = '';

    $length = mb_strlen($str,'utf-8');

    for ($i=0; $i < $length; $i++) {
        $_tmpStr = mb_substr($str,$i,1,'utf-8');
        if(strlen($_tmpStr) >= 4){
            $strEncode .= '[[EMOJI:'.rawurlencode($_tmpStr).']]';
        }else{
            $strEncode .= $_tmpStr;
        }
    }

    return $strEncode;
}

function str2emoji($str){
    $strDecode = preg_replace_callback("/\[\[EMOJI:(.*?)\]\]/", function($matches){
        return rawurldecode($matches[1]);
    }, $str);
    return $strDecode;
}


/**
 * 过滤emoji表情
 * @param type $str
 * @return type
 */
function replace_emoji($str){
    $tmpStr = json_encode($str); //暴露出unicode
    $tmpStr = preg_replace("#(\\\ue[0-9a-f]{3})#ie","",$tmpStr); //将emoji的unicode留下，其他不动
    $new_str = json_decode($tmpStr);
    return $new_str;
}


function replaceNull($string){
    return $string ? $string : '';
}

function replaceNullToArr($arr){
    if(is_array($arr)){
        $data = [];
        foreach($arr as $k=>$v){
            $data[$k] = replaceNull($v);
        }
    }
    return $arr;
}

function makedir($path){
    if(is_dir($path)){//已经是目录了就不用创建
        return true;
    }
    if(is_dir(dirname($path))){//父目录已经存在，直接创建
        return mkdir($path);
    }
    makedir(dirname($path));//从子目录往上创建
    return mkdir($path);//因为有父目录，所以可以创建路径
}


function ToUrlParams($urlObj){
    $buff = "";
    foreach ($urlObj as $k => $v)
    {
        if($k != "sign"){
            $buff .= $k . "=" . $v . "&";
        }
    }

    $buff = trim($buff, "&");
    return $buff;
}


function makeVerify($number){
    $str = md5($number . time());
    $str = substr($str, 0, 6);
    $str = hexdec($str);
    $str = substr($str, 0, 6);
    return str_pad($str, 6, "0");
}


function isAndroid(){
    $ua = $_SERVER['HTTP_USER_AGENT'];//这里只进行IOS和Android两个操作系统的判断，其他操作系统原理一样
    if (strpos($ua, 'Android') !== false) {//strpos()定位出第一次出现字符串的位置，这里定位为0
        preg_match("/(?<=Android )[\d\.]{1,}/", $ua, $version);
        return 1;
    }else{
        return 0;
    }
}

function fullImg($url,$w='',$h='',$format=''){
    if($url == '') return '';
    if(stripos($url,'http') !== false){
        return $url;
    }else{
        if($w || $h || $format) $str = '?imageView/2';
        if($w) $str.='/w/'.$w;
        if($h) $str.='/h/'.$h;
        if($format) $str.='/format/'.$format;
        return \Common\Helper\RequestHelper::IMAGE_URL.$url.$str;
    }
}


function getPrice($price){
    return intval($price);
}


function moneyFormat($money){
    return sprintf("%.2f",$money);
}

function get_tree($list,$pid = 0){
    $tree = [];
    foreach($list as $k=>$v){
        if($v['pid'] == $pid){
            $v['list'] = get_tree($list,$v['id']);
            $tree[] = $v;
        }
    }
    return $tree;
}

function memory_usage() {
    $memory     = ( ! function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2).'MB';
    return $memory;
}